import os
import sys
import pygame
from .game_logic import GameLogic, GameState
from .ui.menu import MainMenu, LevelSelectMenu, LeaderboardMenu
from .ui.game_ui import GameUI, LoginUI

class Game:
    """游戏主类"""
    
    def __init__(self):
        """初始化游戏"""
        # 初始化pygame
        pygame.init()
        
        # 设置屏幕尺寸
        self.screen_width = 800
        self.screen_height = 600
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))
        
        # 设置窗口标题
        pygame.display.set_caption("开心消消乐")
        
        # 设置游戏时钟
        self.clock = pygame.time.Clock()
        
        # 创建游戏逻辑
        self.game_logic = GameLogic(self.screen_width, self.screen_height)
        
        # 创建UI
        self.main_menu = MainMenu(self.screen_width, self.screen_height)
        self.level_menu = None
        self.leaderboard_menu = None
        self.game_ui = GameUI(self.screen_width, self.screen_height)
        self.login_ui = LoginUI(self.screen_width, self.screen_height)
        
        # 游戏状态
        self.running = True
        
        # 登录状态
        self.logged_in = False
        
    def run(self):
        """运行游戏主循环"""
        # 初始化游戏
        self.game_logic.initialize()
        
        # 更新关卡选择菜单
        self.level_menu = LevelSelectMenu(self.screen_width, self.screen_height, self.game_logic.level_data)
        
        # 创建排行榜菜单
        self.leaderboard_menu = LeaderboardMenu(self.screen_width, self.screen_height)
        
        # 主游戏循环
        while self.running:
            # 处理事件
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                    
                if not self._handle_event(event):
                    self.running = False
            
            # 更新游戏状态
            self._update()
            
            # 绘制游戏界面
            self._draw()
            
            # 更新屏幕显示
            pygame.display.flip()
            
            # 控制帧率
            self.clock.tick(60)
            
        # 关闭资源
        self._cleanup()
        
    def _handle_event(self, event):
        """
        处理游戏事件
        
        参数:
            event: pygame事件对象
            
        返回值:
            bool: 是否继续运行游戏
        """
        # 获取鼠标位置
        mouse_pos = pygame.mouse.get_pos()
        
        # 根据游戏状态分发事件
        if self.game_logic.state == GameState.MENU:
            action = self.main_menu.handle_event(event)
            
            if action == 'play':
                if not self.logged_in:
                    self.game_logic.state = GameState.LOGIN
                else:
                    self.game_logic.state = GameState.LEVEL_SELECT
            elif action == 'leaderboard':
                self.game_logic.state = GameState.LEADERBOARD
                
                # 加载排行榜数据
                high_scores = self.game_logic.get_high_scores()
                self.leaderboard_menu.set_leaderboard_data(high_scores)
                
            elif action == 'quit':
                return False
                
        elif self.game_logic.state == GameState.LOGIN:
            action, data = self.login_ui.handle_event(event)
            
            if action == 'login':
                # 尝试登录
                success = self.game_logic.login_player(data['username'], data['password'])
                if success:
                    self.logged_in = True
                    self.game_logic.state = GameState.LEVEL_SELECT
                    self.login_ui.set_status("登录成功！", False)
                else:
                    self.login_ui.set_status("登录失败：用户名或密码错误")
                    
            elif action == 'register':
                # 尝试注册
                success = self.game_logic.register_player(data['username'], data['password'])
                if success:
                    self.logged_in = True
                    self.game_logic.state = GameState.LEVEL_SELECT
                    self.login_ui.set_status("注册并登录成功！", False)
                else:
                    self.login_ui.set_status("注册失败：用户名可能已存在")
                    
            elif action == 'back':
                self.game_logic.state = GameState.MENU
                
        elif self.game_logic.state == GameState.LEVEL_SELECT:
            action, level_id = self.level_menu.handle_event(event)
            
            if action == 'level':
                self.game_logic.start_level(level_id)
            elif action == 'back':
                self.game_logic.state = GameState.MENU
                
        elif self.game_logic.state == GameState.LEADERBOARD:
            action, data = self.leaderboard_menu.handle_event(event)
            
            if action == 'back':
                self.game_logic.state = GameState.MENU
            elif action == 'filter':
                # 更新排行榜筛选
                self.leaderboard_menu.current_level = data
                high_scores = self.game_logic.get_high_scores(data)
                self.leaderboard_menu.set_leaderboard_data(high_scores)
            elif action == 'page':
                # 更新排行榜分页
                self.leaderboard_menu.change_page(data)
                
        elif self.game_logic.state in [GameState.PLAYING, GameState.PAUSED]:
            # 处理游戏内UI事件
            ui_action = self.game_ui.handle_event(event, self.game_logic)
            
            if ui_action == 'pause':
                if self.game_logic.state == GameState.PLAYING:
                    self.game_logic.state = GameState.PAUSED
                else:
                    self.game_logic.state = GameState.PLAYING
                    
            elif ui_action == 'shuffle':
                if self.game_logic.state == GameState.PLAYING and self.game_logic.board:
                    self.game_logic.board.shuffle_board()
                    
            # 处理游戏逻辑事件
            if not self.game_logic.handle_event(event):
                return False
                
        elif self.game_logic.state in [GameState.GAME_OVER, GameState.LEVEL_COMPLETE]:
            # 处理游戏结束事件
            if not self.game_logic.handle_event(event):
                return False
                
        return True
        
    def _update(self):
        """更新游戏状态"""
        # 获取鼠标位置
        mouse_pos = pygame.mouse.get_pos()
        
        # 根据游戏状态更新
        if self.game_logic.state == GameState.MENU:
            self.main_menu.update(mouse_pos)
            
        elif self.game_logic.state == GameState.LOGIN:
            self.login_ui.update(mouse_pos)
            
        elif self.game_logic.state == GameState.LEVEL_SELECT:
            self.level_menu.update(mouse_pos)
            
        elif self.game_logic.state == GameState.LEADERBOARD:
            self.leaderboard_menu.update(mouse_pos)
            
        elif self.game_logic.state == GameState.PLAYING:
            self.game_ui.update(mouse_pos)
            self.game_logic.update()
            
        elif self.game_logic.state == GameState.PAUSED:
            self.game_ui.update(mouse_pos)
            
    def _draw(self):
        """绘制游戏界面"""
        # 根据游戏状态绘制
        if self.game_logic.state == GameState.MENU:
            self.main_menu.draw(self.screen)
            
        elif self.game_logic.state == GameState.LOGIN:
            self.login_ui.draw(self.screen)
            
        elif self.game_logic.state == GameState.LEVEL_SELECT:
            self.level_menu.draw(self.screen)
            
        elif self.game_logic.state == GameState.LEADERBOARD:
            self.leaderboard_menu.draw(self.screen)
            
        elif self.game_logic.state in [GameState.PLAYING, GameState.PAUSED, GameState.GAME_OVER, GameState.LEVEL_COMPLETE]:
            self.game_logic.draw(self.screen)
            
    def _cleanup(self):
        """清理游戏资源"""
        # 关闭数据库连接
        if self.game_logic.db:
            self.game_logic.db.close()
            
        # 退出pygame
        pygame.quit()

def main():
    """主函数"""
    # 添加当前路径到系统路径
    current_dir = os.path.dirname(os.path.abspath(__file__))
    parent_dir = os.path.dirname(current_dir)
    if parent_dir not in sys.path:
        sys.path.insert(0, parent_dir)
        
    # 创建并运行游戏
    game = Game()
    game.run()
    
if __name__ == "__main__":
    main() 